package com.dyn.videohub.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dyn.videohub.Service.UserService;
import com.dyn.videohub.Service.UserTokenService;
import com.dyn.videohub.domain.User;
import com.dyn.videohub.domain.UserInfoVo;
import com.dyn.videohub.domain.UserToken;
import com.dyn.videohub.enums.UserType;
import com.dyn.videohub.mapper.UserMapper;
import com.dyn.videohub.untils.RedisUtil;
import com.dyn.videohub.untils.ValidateCodeUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.dyn.videohub.Common.CommonErrorEnums.*;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserTokenService userTokenService;


    /***
     * 获取当前用户
     * @return
     */
    @Override
    public Long getCurrentUserId() {
        HttpServletRequest request = getRequest();
        assert request != null;
        String token = request.getHeader("token");
        UserToken userToken = userTokenService.getToken(token);
        return userToken.getUserId();
    }

    /**
     * 获得请求
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (!(requestAttributes instanceof ServletRequestAttributes)) {
            return null;
        }
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    public String register(String username, String password) {
        //默认先设置用户type为0，逻辑上因先判断用户注册的用户名是否存在(轮询或者直接提交后排除)
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);
        User user = this.baseMapper.selectOne(lambdaQueryWrapper);
        if (user != null) {
            return USER_ALREADY_EXIST.getName();
        }
        User u = new User();
        u.setUsername(username);
        u.setPassword(password);
        u.setNickName("用户123");
        u.setAvatar("default_avatar.png");
        u.setType(0);
        this.baseMapper.insert(u);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user1 = this.baseMapper.selectOne(queryWrapper);
        return userTokenService.createToken(user1.getUserId());
    }


    /***
     * 用户密码登录
     * @param username 用户名
     * @param password 密码
     * @return token
     */
    public String loginByPassword(String username, String password) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);
        User user = this.baseMapper.selectOne(lambdaQueryWrapper);
        //如果找不到用户
        if (user == null) {
            return NO_USER_ERROR.getName();
        }
        //输入的密码和数据库中不一致
        if (!user.getPassword().equals(password)) {
            return USERNAME_OR_PASSWORD_ERROR.getName();
        }
        return userTokenService.createToken(user.getUserId());
    }

    /***
     * 在此处处理验证码生成，用户短暂映射，将验证码存入redis
     * @param phone
     */
    @Override
    public void SMSCode(String phone) {
        String MessageCode = ValidateCodeUtils.generateValidateCode(4).toString();
        redisUtil.set(phone, MessageCode, 60);
        //发送验证码
//        SMSUtils.sendMessage("瑞吉外卖","SMS_264935808",phone,MessageCode);
    }

    /***
     * 短信验证登录
     * @param phone 手机号
     * @param code 验证码
     * @return 用户基本信息
     */
    public String validateSMSLogin(String phone, String code) {
        if (code.equals(redisUtil.get(phone))) {
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, phone);
            User user = this.baseMapper.selectOne(lambdaQueryWrapper);
            if (user != null) {
                return userTokenService.createToken(user.getUserId());
            } else {
                User u = new User();
                //此处自动注册用户，因此返回默认用户信息即可
                u.setPhone(phone);
                u.setNickName("用户123");
                u.setAvatar("default_avatar.png");
                u.setType(0);
                this.baseMapper.insert(u);
                LambdaQueryWrapper<User> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(User::getPhone, phone);
                User user1 = this.baseMapper.selectOne(lambdaQueryWrapper1);
                return userTokenService.createToken(user1.getUserId());
            }
        }
        return null;
    }

    /***
     * 获取用户基本信息
     * @param token token
     * @return UserInfoVo 用户基本信息
     */
    public UserInfoVo getUserInfo(String token) {
        UserToken userToken = userTokenService.getToken(token);
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        User user = this.baseMapper.selectOne(lambdaQueryWrapper.eq(User::getUserId, userToken.getUserId()));
        return new UserInfoVo(user.getNickName(), user.getAvatar(), UserType.of(user.getType()).getName());
    }
}
